package net.vkits.anjiamiao.domain.service;

import net.vkits.anjiamiao.domain.model.*;
import net.vkits.anjiamiao.domain.repository.ContractRepository;
import net.vkits.anjiamiao.domain.repository.CustomerRepository;
import net.vkits.anjiamiao.domain.repository.OrderRepository;
import net.vkits.anjiamiao.domain.repository.RestrictionsRepository;
import net.vkits.common.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * Created by ethan-liu on 2017/1/14.
 */
@Service
public class CustomerService {
    private static final Logger logger = LoggerFactory.getLogger(OrderService.class);

    @Resource
    private CustomerRepository customerRepository;
    @Resource
    private ContractRepository contractRepository;
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private RestrictionsRepository restrictionsRepository;

    public User getUser(String cellPhoneNum) {
        User user = new User();
        Optional<Customer> customerOptional = customerRepository.findByCellPhoneNumAndDeletedFalse(cellPhoneNum);
        Optional<Contract> contractOptional = contractRepository.findByUserPhoneAndDeletedFalse(cellPhoneNum);
        List<Order> orders = orderRepository.findByCellPhoneNumAndDeletedFalse(cellPhoneNum);
        // TODO 写死的查询，需要改
        Restrictions restrictions = restrictionsRepository.findOne(1L);
        customerOptional.ifPresent(customer -> {
            // 是否黑名单
            user.setIsBlock(customer.getIsBlock());
            // 是否VIP
            user.setIsVIP(customer.getIsVIP());
            // 头像URL
            user.setAvatar(customer.getAvatarUrl());
            // 名字
            user.setName(customer.getName());
            // 用户状态
            user.setIsCertification(customer.getAuthenticationStatus());
        });
        contractOptional.ifPresent(contract -> {
            // 合同状态
            user.setContractStatus(contract.getStatus());
            // 合同是否超过有效期
            if (contract.getStatus().equals(ContractStatus.Verified) && contract.overTime()) {
                user.setContractOverTime(true);
            } else {
                user.setContractOverTime(false);
            }
        });
        // 超月限次不能交易
        long monthOrders = orders.stream()
                .filter(order -> order.getStatus() == TradeStatus.TransferSuccess)
                .filter(order ->
                        order.getCreateTime().getMonth().equals(LocalDateTime.now().getMonth())).count();
        if (restrictions.overMonthTime(monthOrders)) {
            user.setOverMonthTime(false);
        } else {
            user.setOverMonthTime(true);
        }
        // 超日限次不能交易
        long dayOrders = orders.stream()
                .filter(order -> order.getStatus() == TradeStatus.TransferSuccess)
                .filter(order -> order.getCreateTime().getDayOfMonth() == LocalDateTime.now().getDayOfMonth()).count();
        if (restrictions.overDayTime(dayOrders)) {
            user.setOverDayTime(false);
        } else {
            user.setOverDayTime(true);
        }
        // 有未完成订单不能交易
        if (orders.isEmpty()) {
            user.canTrade(true);
        } else {
            orders.forEach(order -> {
                // 有未完成订单（除转账成功、转账失败已退款、风险交易已退款以外的订单状态）不能交易
                if (order.getStatus() == TradeStatus.TransferSuccess ||
                        order.getStatus() == TradeStatus.RiskTradeRefund ||
                        order.getStatus() == TradeStatus.TransferFailedRefund) {
                    user.canTrade(false);
                } else {
                    user.canTrade(true);
                }
            });
        }
        // 交易最低限额
        user.setTradeLimit(restrictions.getTradeLimit());
        return user;
    }

    public void deleteUser(String cellPhoneNum) {
        Optional<Customer> customerOptional = customerRepository.findByCellPhoneNumAndDeletedFalse(cellPhoneNum);
        Optional<Contract> contractOptional = contractRepository.findByUserPhoneAndDeletedFalse(cellPhoneNum);
        List<Order> orders = orderRepository.findByCellPhoneNumAndDeletedFalse(cellPhoneNum);
        customerOptional.ifPresent(customer -> {
            customer.delete();
            customerRepository.save(customer);
        });
        contractOptional.ifPresent(contract -> {
            contract.delete();
            contractRepository.save(contract);
        });
        orders.forEach(Order::delete);
        orderRepository.save(orders);
    }
}
